package tech.mhuang.pacebox.springboot.core.servlet;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 请求过滤器
 *
 * @author mhuang
 * @since 1.0.0
 */
public class RequestFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String contentType = request.getContentType();
        WebServletRequest httpRequest;
        HttpServletResponse httpResponse;
        String method = request.getMethod();
        if ((contentType != null) && (contentType.startsWith("multipart/form-data")) && ("POST".equalsIgnoreCase(method))) {
            httpRequest = new WebRequestHeader(request);
            httpResponse = new WebResponseHeader(response);
        } else {
            httpRequest = new WebRequestStreamHeader(request);
            httpResponse = new WebResponseStreamHeader(response);
        }
        try {
            filterChain.doFilter(httpRequest, httpResponse);
        } finally {
            if (httpResponse instanceof WebResponseStreamHeader) {
                ((WebResponseStreamHeader) httpResponse).copyBodyToResponse();
            }
        }
    }
}
